from .MyException import LosedArgumentException,NotSuppportedTypeException
from ..items import TP_item
import scrapy.item

class DB_operate_4_scrapy_item():
    def __init__(self):
        pass
    def supported_type_juge(self,j_item):
        if not isinstance(j_item,scrapy.item):
            raise NotSuppportedTypeException("not support for is type%s" %type(j_item))

    def insert_one_item_sql(self, one_item):
        self.supported_type_juge(one_item)
        suffix_sql = ''
        keys = one_item.keys()
        values = one_item.values()
        values_palce_holder = ','.join(['%s'] * len(keys))
        fields_sql = ','.join(keys)
        suffix_sql = '(%s) values(%s)' % (fields_sql, values_palce_holder)
        return suffix_sql

    def insert_one_item_full_sql(self, one_item, pre_sql):
        return pre_sql + self.insert_one_item_sql(one_item)

    def insert_many_item_suffix_sql(self, items):
        self.supported_type_juge(items)
        if (len(items)) <= 0:
            return None
        return self.insert_one_item_sql()

    def update_one_by_single_older(self, new_item, table_name=None, old_item=None):
        self.supported_type_juge(new_item)
        self.supported_type_juge(old_item)
        if old_item is None:
            raise LosedArgumentException('缺少需要确定主键位置的参数')
        if table_name is None or len(table_name.strip()) == 0:
            raise LosedArgumentException('表名参数丢失 不能进行使用')

        sql = 'update tablename set  col_name = val,col_name = val2 where id = ? and io = ?'
        col_params = []
        col_params.extend(new_item.keys())
        col_val_params = []
        col_val_params.extend(new_item.values())

        indentified_params = []
        indentified_params.extend(old_item.keys())
        indentified_val_params = []
        indentified_val_params.extend(old_item.values())
        #先渲染固定语句 在渲染?set col_n = val_n 先渲染col_n 再渲染val_n => ?
        sql = 'update %s set %s where %s'%(table_name,str(' = ? , '.join(col_params)),str('= ? and '.join(indentified_params))) + ' = ?'
        vals_params = []
        vals_params.extend(col_val_params)
        vals_params.extend(indentified_val_params)
        print(vals_params)
        sql = sql%indentified_val_params
        #
        print(sql)
        return sql

if __name__ == "__main__":
    tp = TP_item()
    tp['code'] = '1234'
    tp['full_res'] = '5G'
    oldtp = TP_item()
    oldtp['code'] = '111'
    oldtp['full_res'] = 'HUAWEI'

    operator =DB_operate_4_scrapy_item()
    operator.update_one_by_single_older(tp,'wylh_tingpan', old_item=oldtp)
